package mtn.bowen.yan.server.service.impl;

import com.google.common.collect.Maps;
import com.jfoenix.controls.JFXComboBox;
import com.jfoenix.controls.JFXRadioButton;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.PieChart;
import javafx.scene.chart.XYChart;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import mtn.bowen.yan.server.common.Constant;
import mtn.bowen.yan.server.dao.PollsSuggestDao;
import mtn.bowen.yan.server.fx.StageManager;
import mtn.bowen.yan.server.model.FoodRank;
import mtn.bowen.yan.server.model.PictureDishes;
import mtn.bowen.yan.server.model.PollsSuggest;
import mtn.bowen.yan.server.service.JavaFxUiService;
import mtn.bowen.yan.server.service.PictureDishesService;
import mtn.bowen.yan.server.service.PollsSuggestService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.temporal.ChronoField;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author <a href=mailto:yanbowen90@foxmail.com> bowen.yan </a>
 * @version 1.0
 * @description: TODO
 * @date 2021-11-04 6:52 AM
 */
@Component
public class PollsSuggestServiceImpl implements PollsSuggestService {

    private final static Logger LOGGER = LoggerFactory.getLogger(PollsSuggestServiceImpl.class);

    @Resource
    private PictureDishesService pictureDishesService;

    @Resource
    private JavaFxUiService javaFxUiService;

    @Resource
    private PollsSuggestDao pollsSuggestDao;

    /**
     * 按种类显示待投票菜品
     *
     * @param pollsSuggestComboBox 种类
     * @return 带投票菜品集合
     */
    @Override
    public VBox pollsSuggestByKind(JFXComboBox pollsSuggestComboBox) {
        int indexKind = pollsSuggestComboBox.getSelectionModel().getSelectedIndex();
        List<PictureDishes> pictureDishesByKind = pictureDishesService.getPictureDishesByKind(indexKind + 1);
        int allRow = pictureDishesService.getRow(pictureDishesByKind.size(), Constant.DELETE_RECIPE_COLUMN);
        int tempRow = allRow;
        VBox allVBox = new VBox();
        try {
            int count = 0;
            int flag = 0;
            for (int row = 0; row < allRow; row++) {
                HBox hBox = javaFxUiService.getPictureHBox(Pos.CENTER_LEFT, new Insets(10, 10, 10, 10));
                hBox.setSpacing(60);
                if (tempRow >= 2) {
                    for (int col = 0; col < Constant.DELETE_RECIPE_COLUMN; col++) {
                        PictureDishes pictureDishes = pictureDishesByKind.get(flag);
                        VBox vBox = javaFxUiService.getVBox(new Insets(10, 10, 10, 10));
                        ImageView view = javaFxUiService.getImageView(150.0, 150.0, "/picture/" + pictureDishes.getUuid());
                        JFXRadioButton jButton = new JFXRadioButton(pictureDishes.getName());
                        jButton.setStyle("-fx-font-family: STKaiTi;-fx-border-width: 1px;-fx-font-size: 22;");
                        vBox.getChildren().add(view);
                        vBox.getChildren().add(jButton);
                        //设置标志位 set in Map
                        jButton.setId(pictureDishes.getUuid());
                        jButton.setOnAction(event -> {
                            StageManager.pollsSuggestMapDropIfExists(jButton.getId());
                        });
                        hBox.getChildren().add(vBox);
                        count++;
                        flag++;
                    }
                    tempRow--;
                    allVBox.getChildren().add(hBox);
                } else {
                    for (int col = 0; col < pictureDishesByKind.size() - count; col++) {
                        PictureDishes pictureDishes = pictureDishesByKind.get(flag);
                        VBox vBox = javaFxUiService.getVBox(new Insets(10, 10, 10, 10));
                        ImageView view = javaFxUiService.getImageView(150.0, 150.0, "/picture/" + pictureDishes.getUuid());
                        JFXRadioButton jButton = new JFXRadioButton(pictureDishes.getName());
                        jButton.setStyle("-fx-font-family: STKaiTi;-fx-border-width: 1px;-fx-font-size: 22;");
                        vBox.getChildren().add(view);
                        vBox.getChildren().add(jButton);
                        //设置标志位 set in Map
                        jButton.setId(pictureDishes.getUuid());
                        jButton.setOnAction(event -> {
                            StageManager.pollsSuggestMapDropIfExists(jButton.getId());
                        });
                        hBox.getChildren().add(vBox);
                        flag++;
                    }
                    allVBox.getChildren().add(hBox);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return allVBox;
    }

    /**
     * 更新投票建议UI
     *
     * @param ui       带投票UI
     * @param comboBox 带投票集合
     */
    @Override
    public void updatePollsSuggestUi(HBox ui, JFXComboBox comboBox) {
        ui.getChildren().clear();
        VBox vBox = pollsSuggestByKind(comboBox);
        ui.getChildren().add(vBox);
    }

    /**
     * 存储投票建议
     *
     * @param pollsSuggest 投票信息
     */
    @Override
    public void savePollsSuggest(PollsSuggest pollsSuggest) {

        try {
            pollsSuggestDao.insertOnUpdate(pollsSuggest);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("PollsSuggestServiceImpl.savePollsSuggest is error: ", e);
        }
    }

    /**
     * 查询day天前的数据
     *
     * @param day 天数
     * @return 结果集合
     */
    @Override
    public List<PollsSuggest> selectByDay(Integer day) {
        List<PollsSuggest> result = null;
        try {
            result = pollsSuggestDao.selectBeforeSevenDay(day);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("PollsSuggestServiceImpl.selectByDay is error: ", e);
        }
        return result;
    }

    /**
     * 获取每日投票次数
     *
     * @param day 天数
     */
    @Override
    public Map<Integer, List<PollsSuggest>> getPollsNumByDay(Integer day) {

        Map<Integer, List<PollsSuggest>> hashMap = Maps.newHashMap();
        //今天投票数
        List<PollsSuggest> todayNum = selectByDay(Constant.ZERO);
        hashMap.put(Constant.ZERO, todayNum);

        for (int num = 1; num <= day; num++) {
            List<PollsSuggest> find = selectByDay(num);
            List<PollsSuggest> before = selectByDay(num - 1);
            find.removeAll(before);
            hashMap.put(num, find);
        }

        return hashMap;
    }

    /**
     * 构造折线统计图
     *
     * @param lineChart 图
     */
    @Override
    public void createLineChart(LineChart<String, Number> lineChart, Map<Integer, List<PollsSuggest>> pollsNumByDay) {


        XYChart.Series<String, Number> series = new XYChart.Series<>();
        series.setName("投票数");
        int year = LocalDateTime.now().get(ChronoField.YEAR);
        int month = LocalDateTime.now().get(ChronoField.MONTH_OF_YEAR);
        int day = LocalDateTime.now().get(ChronoField.DAY_OF_MONTH);
        for (int count = 0; count <= Constant.POLLS_WEEK_DAY; count++) {

            if (pollsNumByDay.get(count) != null && pollsNumByDay.get(count).size() != 0) {
                series.getData().add(new XYChart.Data<>(year + "-" + month + "-" + day, pollsNumByDay.get(count).size()));
            } else {
                series.getData().add(new XYChart.Data<>(year + "-" + month + "-" + day, 0));
            }
            LocalDateTime localDateTime = LocalDateTime.now().minusDays(count + 1);
            year = localDateTime.get(ChronoField.YEAR);
            month = localDateTime.get(ChronoField.MONTH_OF_YEAR);
            day = localDateTime.get(ChronoField.DAY_OF_MONTH);
        }
        lineChart.getData().setAll(series);
        lineChart.setCreateSymbols(true);
    }

    /**
     * 构造饼图
     *
     * @param pieChart 饼图对象
     */
    @Override
    public void createPieChart(PieChart pieChart) {

        Map<String, FoodRank> rankMap = selectPollsInfo(7);
        ObservableList<PieChart.Data> pieChartData = FXCollections.observableArrayList();
        rankMap.forEach((kev, value) -> {
            pieChartData.add(new PieChart.Data(value.getName(), value.getCount().doubleValue()));
        });
        pieChart.setData(pieChartData);
        pieChart.setClockwise(false);
    }

    /**
     * 查询day天内 点赞 投票信息
     *
     * @param day 天数
     * @return 投票信息
     */
    @Override
    public Map<String, FoodRank> selectPollsInfo(Integer day) {
        Map<String, FoodRank> hashMap = Maps.newHashMap();
        List<PollsSuggest> pollsSuggests = pollsSuggestDao.selectBeforeSevenDay(day);
        pollsSuggests.forEach((item) -> {
            //判断 state, 统计点赞菜品，后期可以增加拍砖菜品统计
            if (item.getState()) {
                if (hashMap.containsKey(item.getUuid())) {
                    FoodRank rank = hashMap.get(item.getUuid());
                    int temp = rank.getCount() + 1;
                    rank.setCount(temp);
                } else {
                    FoodRank build = FoodRank.builder().uuid(item.getUuid()).kind(item.getKind()).name(item.getName()).chef(item.getChef()).state(item.getState()).count(1).build();
                    hashMap.put(item.getUuid(), build);
                }
            }
        });
        return hashMap;
    }
}
